package com.zhupanlin.zhyl.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhupanlin.zhyl.common.exception.Zhylxception;
import com.zhupanlin.zhyl.common.result.ResultCodeEnum;
import com.zhupanlin.zhyl.common.utils.AuthContextHolder;
import com.zhupanlin.zhyl.common.utils.JwtHelper;
import com.zhupanlin.zhyl.enums.AuthStatusEnum;
import com.zhupanlin.zhyl.model.user.Patient;
import com.zhupanlin.zhyl.model.vo.user.LoginVo;
import com.zhupanlin.zhyl.model.vo.user.UserAuthVo;
import com.zhupanlin.zhyl.user.mapper.UserInfoMapper;
import com.zhupanlin.zhyl.user.service.PatientService;
import com.zhupanlin.zhyl.user.service.UserInfoService;
import com.zhupanlin.zhyl.model.user.UserInfo;
import com.zhupanlin.zhyl.vo.user.UserInfoQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/12/1 12:34
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private PatientService patientService;

    /**
     * 用户手机号登录接口
     *
     * @param loginVo
     * @return
     */
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();

        // 判断手机号和验证码是否为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new Zhylxception(ResultCodeEnum.PARAM_ERROR);
        }

        // 判断手机验证码和输入的验证码是否一致
        String redisCode = redisTemplate.opsForValue().get(phone);
        if (!code.equals(redisCode)) {
            throw new Zhylxception(ResultCodeEnum.CODE_ERROR);
        }

        // 绑定手机号码
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(loginVo.getOpenid())) {
            userInfo = selectWxInfoByOpenId(loginVo.getOpenid());
            if (userInfo != null) {
                userInfo.setPhone(loginVo.getPhone());
                updateById(userInfo);
            } else {
                throw new Zhylxception(ResultCodeEnum.DATA_ERROR);
            }
        }

        // 如果 userInfo 为空
        if (userInfo == null) {
            // 判断是否第一次登录：注册
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            userInfo = baseMapper.selectOne(wrapper);
            if (userInfo == null) {
                // 第一次使用手机号进行登录
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            } else {
                if (userInfo.getStatus() == 0) {
                    throw new Zhylxception(ResultCodeEnum.LOGIN_DISABLED_ERROR);
                }
            }
        }

        // 不是：进行登录

        // 返回登录信息

        // 返回登录用户名

        // 返回token
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);

        // TOKEN 生成
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    /**
     * 判断数据库中是否已经存在
     *
     * @param openid
     * @return
     */
    @Override
    public UserInfo selectWxInfoByOpenId(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid", openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    /**
     * 用户认证接口
     *
     * @param userAuthVo
     * @param request
     */
    @Override
    public void userAuth(UserAuthVo userAuthVo, HttpServletRequest request) {
        // 根据用户id查询用户信息
        UserInfo userInfo = baseMapper.selectById(AuthContextHolder.getUserId(request));
        // 设置认证信息
        userInfo.setName(userInfo.getName());
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userInfo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(1);

        // 进行信息更新
        baseMapper.updateById(userInfo);
    }

    /**
     * 用于列表（条件查询分页）
     *
     * @param pageParam
     * @param userInfoQueryVo
     * @return
     */
    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        String name = userInfoQueryVo.getKeyword();
        Integer status = userInfoQueryVo.getStatus();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();

        // 对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like("name", name);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.like("status", status);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            wrapper.like("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time", createTimeEnd);
        }

        IPage<UserInfo> pages = baseMapper.selectPage(pageParam, wrapper);

        // 翻译
        pages.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return pages;
    }

    /**
     * 用户锁定
     *
     * @param userId
     * @param status
     */
    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue() == 0 || status.intValue() == 1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }

    /**
     * 用户详情
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> show(Long userId) {
        Map<String, Object> map = new HashMap<>();
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo = this.packageUserInfo(userInfo);
        map.put("userInfo", userInfo);
        // 根据userId查询就诊人信息
        List<Patient> patientList = patientService.findAllUserId(userId);
        map.put("patientList", patientList);

        return map;
    }

    /**
     * 认证审批 2 通过 -1 不通过
     *
     * @param userId
     * @param authStatus
     */
    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus.intValue() == 2 || authStatus.intValue() == -1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    private UserInfo packageUserInfo(UserInfo userInfo) {

        // 处理认证状态编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        String statusString = userInfo.getStatus().intValue() == 0 ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        return userInfo;
    }
}
